package com.hf.action;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.hibernate.*;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;

import tool.ClientTool;
import tool.HtmlTool;
import tool.JsonTool;
import tool.StringTool;
import tool.TimeTool;

import com.base.bean.*;
import com.base.dao.*;
import com.base.domain.ClientDetail;
import com.base.service.*;
import com.base.service.AddressService.ADD_TYPE;
import com.base.service.client.AdvanceClientService;
import com.base.service.client.ClientFormBean;
import com.hf.bean.ClientFilter;
import com.hf.bean.SimpleAddress;

public class ClientAction6 extends BaseAction {

	// openId(already)
	// tip（共查询到100条(姓名包含[某某])）

	// 查询客户用到的参数
	
	private String orderType; // 排序条件
	private String queryType; // 查询条件
	private String isDesc; // 是否逆序
	private String queryStr; // 查询内容（不填/姓名/电话/某某省 通过正则表达式自动识别）
	
	private Integer curPage; // 当前页码
	private Integer pageSize; // 每页记录数
	private Integer totalPage; // 页数
	private Integer total, phoneNum; // 总记录数

	// 导航用到的参数
	/**
	 * @pramati.0:query 1:add 2:edit 3:createActivity 4:seen已阅
	 */
	private Integer state; // 操作类型 eg：0-query 1-add 2-edit 3-createActivity
	private String url; // 由不同的state对应不同的url
	// openId

	// 新增客户用到的参数
	private Integer cid; // 当前cid （放在隐藏域中）
	private String phone1, phone2, phone3;
	private Integer phone1Id, phone2Id, phone3Id;
	private String provinceId, cityId, areaId;
	private String name, company, memo;
	private String[] chose1, chose2, chose3; // 多选
	private String chose4, chose5; // 单选
	private Integer chose6; // 单选
	private ClientDetail clientDetail;

	// 实时显示客户详情
	private List<ClientDetail> clientList; // 当页的客户详情
	private String cjsons; // clientList转化为json 供kh_show2.jsp(客户详细信息)使用
	
	// 参数初始化
	private int _pageNum;	//每页记录数
	private int _maxNum;	//查询最大记录数

	public ClientAction6() {
		this._pageNum=10;
		this._maxNum=5000;
	}


	
	/**
	 * 功能：
	 * 1)默认显示客户列表每页_pageNum 不超过_maxNum
	 * 2)根据state值来判定导向的页面
	 * 
	 * 
	 */
	public String execute() {	
		this.init(false);	//不刷新
		
		// 正式部署取消下句
//		this.openId = "olWUvt186RJV4_obaeMV5SGT4e2g";
		 
		if (this.openId.equals("")) {
			this.tip = "用户登录异常";
			return ERROR;
		}
		
		User user=UserService.getInstance().getByOpenId(this.openId);
		
		
		String result = ERROR; // 默认返回值

		switch (this.state) {
		
		case 0: 	//默认显示客户列表
			int i = this.show();
//			System.out.println(i);
			if(i>0){
				result = "showClientList";
			}else{
				this.tip="获取客户列表异常~"+this.tip;  // 有可能本来就没有客户
				this.init(true);	//刷新cid等
				this.state=2;
				result="modifyClient";
			}	
			break;
			
		case 1:		//新增客户
			this.init(true);	//刷新cid等
			this.state=2;
			result="modifyClient";
	
		case 2: 	//新增客户Do	（还需要将state=4 同时根据cid显示detail）
			if(this.editCheck(true)>0){		//后台验证通过
				this.merge(user.getUid(), 1);
				this.showDetail(this.cid, user.getUid());
				this.state=4;
				result = "modifyClient";
			}
			break;
			
		case 3: 	//修改客户(只需要根据cid显示detail 同时将state=4 就行)
			this.showDetail(this.cid, user.getUid());
			this.state=4;
			result = "modifyClient";
			break;
			
		case 4: 	//修改客户Do
			if(this.editCheck(false)>0){	//后台验证通过	
//				System.out.println(this.editCheck(false));
				this.merge(user.getUid(), 2);
				result = "modifyClient";
			}else
				this.tip="姓名或电话异常："+this.tip;
			break;	
			
		case 5:		//新增行动（只需要将cid传递过去即可）
			if(this.cid!=0){
				result = "addActvt";
			}
			break;
			
		case 6:		//已阅（只需要将cid传递过去即可）
			if(this.cid!=0){
				this.tip="已阅待实现";
				result = "seen";
			}
			break;	

		}

//		System.out.println("#############################");
//		System.out.println(queryType);
		
		return result;

	}

	
//	public void addTest(){
//		this.state=2;
//		this.openId = "olWUvt186RJV4_obaeMV5SGT4e2g";
//		this.chose6=0;
//		
//		this.cid=0; // 当前cid （放在隐藏域中）
//		this.phone1="15982079516";
//		
//		this.name="张三";
//		
//	}
	
	
	/**
	 * 
	 */
	public static void main(String[] args) throws Exception {
		ClientAction6 c=new ClientAction6();
		c.init(true);
		//c.addTest();
		c.execute();
		System.out.println(c.tip);
		
		
		
		
		
//		int owner = 1;
////		int state=2;
//		String queryStr = "张";
//		String queryType = "c"; // 查询条件： a:默认 b:phone c:name d:addressName
//		boolean isDesc = true;
//		int maxCount = 1000;
//		String orderType = "a"; // 排序条件 a:修改时间 b:达成期限 c:客户分类
//		int state = 2; // 1:province 2:city
//		List<Integer> cids = ClientAction6.getCidList(owner, queryStr,
//				queryType, orderType, state, maxCount, isDesc);
//		//cids = cids.subList(0, 2);
//		for (Integer i : cids) {
//			System.out.println(i);
//		}
	}
	
	// ###################  私有方法     #############################

	private void init(boolean isRefresh){
		this.provinceId=(this.provinceId==null?"0":this.provinceId);
		this.cityId=(this.cityId==null?"0":this.cityId);
		this.areaId=(this.areaId==null?"0":this.areaId);
		this.chose6=(this.chose6==null?0:this.chose6);
		
		
		if(!isRefresh){
			this.tip = "";
			this.state = (this.state == null ? 0 : this.state);
			this.openId = (this.openId == null ? "" : this.openId);
			this.phone1 = (this.phone1 == null ? "" : this.phone1.replaceAll(
					"\\s*", ""));
			this.phone2 = (this.phone2 == null ? "" : this.phone2.replaceAll(
					"\\s*", ""));
			this.phone3 = (this.phone3 == null ? "" : this.phone3.replaceAll(
					"\\s*", ""));
			
			this.phone1Id=(this.phone1Id==null?0:this.phone1Id);
			this.phone2Id=(this.phone2Id==null?0:this.phone2Id);
			this.phone3Id=(this.phone3Id==null?0:this.phone3Id);
			
			this.name = (this.name == null ? "" : this.name.replaceAll("\\s*", ""));
			this.company = (this.company == null ? "" : this.company.replaceAll(
					"\\s*", ""));
			this.memo = (this.memo == null ? "" : this.memo.replaceAll("\\s*", ""));
			this.cid = (this.cid == null ? 0 : this.cid);
		}else{
			this.tip = "";
			this.state = 0;
			
			this.phone1 = "";
			this.phone2 = "";
			this.phone3 = "";
			
			this.phone1Id=0;
			this.phone2Id=0;
			this.phone3Id=0;
			
			this.name = "";
			this.company = "";
			this.memo = "";
			this.cid = 0;
			this.clientDetail=new ClientDetail();
	
		}
	}
	
	
	
	/**
	 * 客户按id显示
	 * @return
	 */
	private boolean showDetailByCid(Integer cid,Integer owner) {
		if(this.showDetail(cid,owner)<0)
			return false;
		return true;
	}

	// 客户管理入口 主要是默认查询或者按条件查询 查询list 或 查询detail
	private int show() {

		final int maxCount = this._maxNum;

		// init
		this.tip = "";
		this.openId = (this.openId == null ? "" : this.openId);

		this.queryType = "a"; // 每次都初始化为a a:默认 b:phone c:name d:addressName
		this.orderType = (this.orderType == null ? "a" : this.orderType); 	// 排序条件
																			// a：默认（修改时间倒序）
																			// b：达成期限
																			// c：客户分类

		if (!this.orderType.equals("a")) {
			this.tip = "按期限、分类排序功能还有待实现";
			return -1;
		}

		this.total = 0;
		this.totalPage = 0;

		this.pageSize = (this.pageSize == null ? this._pageNum : this.pageSize); // 默认每页_pageNum条记录数
		this.queryStr = (this.queryStr == null ? "" : this.queryStr.replaceAll(
				"\\s*", "")); // 查询字符串去空格
		this.isDesc = (this.isDesc == null ? "a" : this.isDesc); // a:desc(倒序)
																	// b:asc

		this.curPage = (this.curPage == null ? 0 : this.curPage); // 当前页
		this.state = (this.state == null ? 0 : this.state); // a:查询list
															// b:查询detail

		// 根据queryStr生成queryType的值（a:默认 b:省 c:name d:phone）
		boolean isHanzi = false;
		boolean isNumber = false;
		boolean isAddressName = false;
	
		
		String lastHanzi = "";
		int addType = 0;
		
		
		
		

		if (this.queryStr.equals("")) {
			this.queryType = "a";
		} else {
			String reg = "[\\u4e00-\\u9fa5]+";// 表示+表示一个或多个中文
			isHanzi = queryStr.matches(reg);
			
//			System.out.println("###################################");
//			System.out.println("isHanzi:"+isHanzi);

			reg = "^[0-9]*$";
			isNumber = queryStr.matches(reg);

			lastHanzi = queryStr.substring(queryStr.length() - 1);
			if (lastHanzi.equals("省"))
				addType = 1;
			else if (lastHanzi.equals("市"))
				addType = 2;
			else if (lastHanzi.equals("区"))
				addType = 3;

			if (addType > 0)
				isAddressName = true;
		}

		// a:null
		if (isNumber)
			this.queryType = "b"; // phone
		else if (isAddressName) {
			this.queryType = "d"; // addName
		} else if (isHanzi) {
			this.queryType = "c"; // name
		}

//		System.out.println("#############################");
//		System.out.println(queryType);
		
		
		if (this.openId.equals("")) {
			this.tip = "请重新登录";
			return -1;
		}

		User user = UserService.getInstance().getByOpenId(this.openId);
		List<Integer> cids = new ArrayList<Integer>();
		// 进行查询
		
		cids = getCidList(user.getUid(), queryStr, queryType, orderType, 0,
					maxCount, true);
		
		if (cids.size() >= maxCount) {
			this.tip = "查询结果大于" + maxCount + "条";
		} else {
			this.tip = "共" + cids.size() + "条数据";
		}
		
//		System.out.println(this.tip);

		this.total = cids.size();
		

		// 按页显示详细

		if (cids.size() < 1) {
//			this.tip = "没有查询到数据";
			if(this.findFullPhone()>0){
			this.cjsons = HtmlTool.getInstance().htmlClientDetail(clientList)
					.toString();
				
				return 1;
			}else{
				this.tip = "没有对应的客户("+this.queryStr+")您可以返回后新建此客户";
				return -1;
			}
				
		}

		this.totalPage = (cids.size()+this.pageSize-1) / this.pageSize;	//总页数
		
		
		int start = this.curPage * this.pageSize;
		int end = (this.curPage + 1) * this.pageSize;
		if (start > cids.size()) {
			this.tip = "页码超出范围,当前已是最后一页";
			start = cids.size();
		} else if (end > cids.size()) {
			this.tip = "当前为最后一页";
			end = cids.size();
			cids = cids.subList(start, end);
		} else {
			cids = cids.subList(start, end);
		}
		this.clientList = new ArrayList<ClientDetail>();

		ClientService cs = ClientService.getInstance();
		for (Integer cid : cids) {
			ClientDetail cd = new ClientDetail();
			ClientBase cb = cs.getClientBaseDao()
					.findByHql("from ClientBase cb where cb.cid=" + cid).get(0);
			ClientExtend ce = cs.getClientExtendDao()
					.findByHql("from ClientExtend ce where ce.cid=" + cid)
					.get(0);
			List<ClientPhone> cps = cs.getClientPhoneDao().findByHql(
					"from ClientPhone cp where cp.state=1 and cp.cid=" + cid);
			cd.setClientBase(cb);
			cd.setClientExtend(ce);
			cd.setClientPhones(cps);
			if (ce.getSellPlan() != null) // 欲购机期限%
				cd.setSellPlanRate(TimeTool.fromTodayRate(ce.getSellPlan(), 100));
			else
				cd.setSellPlanRate(-1); // 没有
			this.clientList.add(cd);

		}

		
		
		
		
		// clientList to JsonStr
		this.cjsons = HtmlTool.getInstance().htmlClientDetail(clientList)
				.toString();
//		System.out.println(this.cjsons);
		
		return 1;

	}
	
	
	
	
	/**
	 * 
	 * @param isAddMode
	 * @return >0:true  <0:false
	 */
	public int editCheck(boolean isAddMode) {
		// check start （后台check 前台通过ajaxcheck）
		ClientService cs = ClientService.getInstance();
		boolean result = false; // 此处值没用

		try {
			if (!isAddMode) {
				result = true; // 修改态的验证结果初始值

				if (!phone1.equals("") && phone1Id == 0) { // 修改时候新增电话都要验证通过
					if (cs.checkPhone(phone1) > 0)
						result = result || true;
					else if (!phone1.equals(""))
						result = false;
				}

				if (!phone2.equals("") && phone2Id == 0) {
					if (cs.checkPhone(phone2) > 0)
						result = result || true;
					else if (!phone2.equals(""))
						result = false;
				}

				if (!phone3.equals("") && phone3Id == 0) {
					if (cs.checkPhone(phone3) > 0)
						result = result || true;
					else if (!phone3.equals(""))
						result = false;
				}

				// 不能每个电话号码都是删除状态或为空
				if ((phone1Id < 0 || phone1.equals(""))
						&& (phone2Id < 0 || phone2.equals(""))
						&& (phone3Id < 0 || phone3.equals(""))) {
					result = false;
					this.tip="[该客户必须至少存在一条电话号码]";
					// System.out.println("??");
				}

			}

			else if (isAddMode) { // 新增模式验证每个电话不为空时,都能验证通过
				result = false;
				
				if(this.provinceId.equals("0") && this.cityId.equals("0") && this.areaId.equals("0")){
					this.tip="[省市区不能同时为空]";
					return -1;
				}

				if (!phone1.equals(""))
					if (cs.checkPhone(phone1) > 0)
						result = result || true;
					else
						result = false;

				if (!phone2.equals("")) // 新增模式 验证每个电话不为空 时验证通过
					if (cs.checkPhone(phone2) > 0)
						result = result || true;
					else
						result = false;

				if (!phone3.equals("")) // 新增模式 验证每个电话不为空 时验证通过
					if (cs.checkPhone(phone3) > 0)
						result = result || true;
					else
						result = false;

			}

			
//			if(!cs.isNameCityRepeat(this.name, this.cityId,this.cid)){	//验证姓名与city是否同时重复，传入cid排除了修改的特殊情况
//				this.tip="[禁止相同城市出现相同姓名]";
//				result = result && false;
//			}
			
		} catch (Exception e) {
			this.tip = "[未知错误 请联系管理员]";
			result = result && false;
			return -1;
		}

		if (!result) { // 后台验证未能通过
//			this.tip = "姓名或电话异常:"+this.tip;
			return -1;
		}

		return 1;
		// check end
	}

	/**
	 * 私有方法： 显示客户详细信息
	 * 
	 * @param cid
	 * @param owner
	 * @return 1:成功 －1:未找到 －2:异常
	 */

	private int showDetail(Integer cid, Integer owner) {
		ClientService cs = ClientService.getInstance();
		this.clientDetail = new ClientDetail();
		this.tip = "";
		try {
			List<ClientBase> cbs = cs.getClientBaseDao().findByHql(
					"from ClientBase cb where cb.cid=" + cid + " and cb.owner="
							+ owner);
			ClientBase cb = null;
			ClientExtend ce = null;
			List<ClientPhone> cps = null;
			if (cbs.size() > 0) {
				cb = cbs.get(0);
				ce = cs.getClientExtendDao()
						.findByHql("from ClientExtend ce where ce.cid=" + cid)
						.get(0);
				// 按创建时间逆序
				cps = cs.getClientPhoneDao().findByHql(
						"from ClientPhone cp where cp.state=1 and cp.cid="
								+ cid + " order by cp.created desc");
				this.clientDetail.setClientBase(cb);
				this.clientDetail.setClientExtend(ce);
				this.clientDetail.setClientPhones(cps);
				this.phoneNum = cps.size(); // 辅助jsp页面的图标显示
				return 1;
			} else {
				this.tip = "您所拥有的客户群中未找该客户";
				return -1;
			}
		} catch (Exception e) {
			this.tip = "出现异常，请联系管理员";
			e.printStackTrace();
			return -2;
		}
	}

	/**
	 * 模糊查询客户cid list的工具类(orderType=b or c 还未实现)
	 * 
	 * @param queryStr
	 *            查询内容（phone 或 name 或 addressName）
	 * @param queryType
	 *            查询条件： a:默认 b:phone c:name d:addressName
	 * @param orderType
	 *            排序条件 a:修改时间 b:达成期限 c:客户分类
	 * @param state
	 *            当queryType=d时 1:province 2:city
	 * @param maxCount
	 *            查询上限 最好为1000
	 * @return 获取查询结果cids
	 */
	private static List<Integer> getCidList(int owner, String queryStr,
			String queryType, String orderType, int state, int maxCount,
			boolean isDesc) {
		//System.out.println(queryType);

		List<Integer> cids = new ArrayList<Integer>();
		queryStr = queryStr.replaceAll("\\s*", ""); // 替换空格
		//System.out.println(queryStr);

		// 根据查询条件获取cid List
		Session session = null;
		try {
			session = ClientService.getInstance().getClientBaseDao()
					.getSessionFactory().getCurrentSession();
			Criteria criteria = null;
			Transaction tx = null;

			// try begin
			tx = session.beginTransaction();

			// 设置查询条件
			criteria = session.createCriteria(ClientBase.class);
			criteria.add(Restrictions.eq("owner", owner)); // 属于自己的
			criteria.add(Restrictions.eq("state", 1)); // state=1 有效状态

			if (queryType.equals("b") && !queryStr.equals("")) { // query phone 需要关联查询
				criteria = session.createCriteria(ClientPhone.class);
				criteria.add(Restrictions.eq("owner", owner)); // 自己创建的
				criteria.add(Restrictions.eq("state", 1)); // state=1 有效状态
				criteria.add(Restrictions.sqlRestriction("{alias}.phone  not like '#%'"));
				criteria.add(Restrictions.like("phone", queryStr,
						MatchMode.ANYWHERE));
				
				
				
			}

			else if (queryType.equals("c") && !queryStr.equals("")) { // name
				criteria.add(Restrictions.like("name", queryStr,
						MatchMode.ANYWHERE));
			}

			else if (queryType.equals("d") && !queryStr.equals("")) { // address
				if (state == 1) {
					criteria.add(Restrictions.like("province", queryStr,
							MatchMode.ANYWHERE));
				} else if (state == 2) {
					criteria.add(Restrictions.like("city", queryStr,
							MatchMode.ANYWHERE));
				}

			}

			// 当以修改时间作为排序条件
			if (orderType.equals("a") ) { // 修改时间  
				
				if(!queryType.equals("b")){	// clientPhone没有修改时间字段
					if (isDesc)
						criteria.addOrder(Order.desc("modified"));
					else
						criteria.addOrder(Order.asc("modified"));
				}

				ProjectionList proList = Projections.projectionList();// 设置投影集合
																		// cid
				proList.add(Projections.groupProperty("cid"));
				criteria.setProjection(proList);
				criteria.setFirstResult(0); // 设置查询上限为1000
				criteria.setMaxResults(maxCount);
				cids = criteria.list();
			}

			// 此功能待完成
			if (orderType.equals("b") || orderType.equals("c")) { // 达成期限 or
																	// 客户分类

			}
			tx.commit();

		} finally {
			if (session.isOpen())
				session.close();
		}
		return cids;
	}

	/**
	 * 
	 * @param creatorId
	 * @param oppType
	 *            1:add 2:modify
	 * @return <1 error 1:success
	 */
	private int merge(Integer creatorId, Integer oppType) {
		// this.initData();

		boolean isOwn = false;
		ClientBase cb = null;
		List<ClientPhone> cps = null;
		this.chose6=(this.chose6==null?0:this.chose6);

		// clientExtend 无论如何都可以写入（不管是否是由自己创建的）
		ClientExtend ce = new ClientExtend();
		ce.setCid(this.cid);
		ce.setModified(TimeTool.getCurrentTime());
		ce.setMemo(memo);
		ce.setOwner(creatorId);
		ce.setYywjj(StringTool.arrToStr(chose1));
		ce.setYyzzj(StringTool.arrToStr(chose2));
		ce.setYgsbType(StringTool.arrToStr(chose3));
		ce.setClientType(chose4);
		ce.setIsZan(chose5);
		

		cb = new ClientBase();
		cb.setCid(cid);
		cb.setProvinceId(provinceId);
		cb.setCityId(cityId);
		cb.setAreaId(areaId);

		AddressService as = AddressService.getInstance();
		if (!provinceId.equals("0"))
			cb.setProvince(as.getNameByCode(ADD_TYPE.PROVINCE, provinceId));
		if (!cityId.equals("0"))
			cb.setCity(as.getNameByCode(ADD_TYPE.CITY, cityId));
		if (!areaId.equals("0"))
			cb.setArea(as.getNameByCode(ADD_TYPE.AREA, areaId));

		cb.setName(this.name);
		cb.setComName(this.company);
		cb.setModified(TimeTool.getCurrentTime());
		cb.setCreator(creatorId);
		cb.setOwner(creatorId);
		cb.setState(1);

		cps = new ArrayList<ClientPhone>();
		ClientPhone cp1 = new ClientPhone();
		cp1.setCid(cid);
		cp1.setCreator(creatorId);
		cp1.setState(1);
		cp1.setPhone(phone1);
		cp1.setId(phone1Id);
		cp1.setCreated(TimeTool.getCurrentTime());

		ClientPhone cp2 = new ClientPhone();
		cp2.setCid(cid);
		cp2.setCreator(creatorId);
		cp2.setState(1);
		cp2.setPhone(phone2);
		cp2.setId(phone2Id);
		cp2.setCreated(TimeTool.getCurrentTime());

		ClientPhone cp3 = new ClientPhone();
		cp3.setCid(cid);
		cp3.setCreator(creatorId);
		cp3.setState(1);
		cp3.setPhone(phone3);
		cp3.setId(phone3Id);
		cp3.setCreated(TimeTool.getCurrentTime());

		cps.add(cp1);
		cps.add(cp2);
		cps.add(cp3);

		ClientExtend ce0 = null;
		Session session = ClientService.getInstance().getClientBaseDao()
				.getSessionFactory().getCurrentSession();
		Criteria criteria = null;
		Transaction tx = null;
		try {
			tx = session.beginTransaction();

			// modify start
			if (oppType == 2 && cid != 0) {
				//System.out.println("####");
				criteria = session.createCriteria(ClientExtend.class);
				criteria.add(Restrictions.eq("cid", Math.abs(this.cid))); // cid
																			// 有可能是负数
				ce0 = (ClientExtend) criteria.list().get(0);
				ce.setId(ce0.getId());
				ce.setCreated(ce0.getCreated());
				
				if (chose6 != 0){
					if(chose6!=99){
						ce.setSellPlan(TimeTool.nMonthLeater(chose6));
					}else
						ce.setSellPlan(null);
					
				}
				else
					ce.setSellPlan(ce0.getSellPlan());	//如果选择空/0 则计划购机时间不变
				
				session.merge(ce);

				criteria = session.createCriteria(ClientBase.class);
				criteria.add(Restrictions.eq("cid", this.cid));
				ClientBase cb0 = (ClientBase) criteria.list().get(0);

				if (cb0.getCreator().equals(creatorId)) {
					isOwn = true;
					//System.out.println(isOwn);
				}

				if (isOwn) {
					// addressId不变的情况
					if (provinceId.equals("0") && cityId.equals("0")
							&& areaId.equals("0")) {
						cb.setProvinceId(cb0.getProvinceId());
						cb.setProvince(cb0.getProvince());
						cb.setCityId(cb0.getCityId());
						cb.setCity(cb0.getCity());
						cb.setAreaId(cb0.getAreaId());
						cb.setArea(cb0.getArea());
					}

					cb.setCreated(cb0.getCreated()); // 创建时间还是保持不变
					cb.setOriginId(cb0.getOriginId());
					cb.setModifier(creatorId); // clientBase只有创建人能够修改
					session.merge(cb);

					// phone modify start
					for (ClientPhone p : cps) { // 修改电话（电话只能作废 新增 不能修改）
						p.setOwner(creatorId);
						if (p.getPhone().equals(""))
							continue;

						if (p.getId() != 0) {

							criteria = session
									.createCriteria(ClientPhone.class);
							criteria.add(Restrictions.eq("id",
									Math.abs(p.getId()))); // 注意：作废的电话id为负数
							ClientPhone cp0 = (ClientPhone) criteria.list()
									.get(0);

							if (p.getId() > 0) { // 这种情况不允许出现（因为phone只能新增或者作废）
								p.setCreated(cp0.getCreated()); // 这样是否修改的时候就不会修改该项目？？
								session.merge(p);

							} else if (p.getId() < 0) {
								cp0.setPhone("#" + cp0.getPhone());
								cp0.setState(2); // 作废状态
								cp0.setWasted(TimeTool.getCurrentTime()); // 作废时间
								session.merge(cp0); // 不能真正的删除
							}

						} else
							session.merge(p); // add new phone

					}
					// phone modify end

				} else
					this.tip = "非本人创建的客户不能修改客户基本信息";
			} // modify end

			// add start
			else if (oppType == 1 && cid == 0) {
				cb.setCreated(TimeTool.getCurrentTime());
				cb.setOriginId(0); // 非推荐客户
				session.save(cb);
				@SuppressWarnings("unchecked")
				List<Integer> results = session
						.createCriteria(ClientBase.class)
						.setMaxResults(1)
						.setProjection(
								Projections.projectionList().add(
										Projections.max("cid"))

						).list();
				Integer maxId = results.get(0);

				ce.setId(0); // 会自动生成主键
				ce.setCreated(TimeTool.getCurrentTime());
				ce.setCid(maxId);
				this.cid = maxId;
				ce.setState(1);
				session.merge(ce);

				for (ClientPhone p : cps) {
					if (p.getPhone().equals(""))
						continue;
					p.setCid(maxId); // 将cid写入
					p.setId(null);
					p.setOwner(creatorId);
					session.save(p);
				}

			} // add end
			else {
				this.tip = "请检查初始条件是否正确！";
				return -2;
			}

			tx.commit();
			this.tip = "修改或添加成功！";
			return 1;
		} catch (Exception e) {
			tx.rollback();
			this.tip = "修改或添加失败";
			e.printStackTrace();
			return -1; // 修改或添加失败
		} finally {
			if (session.isOpen())
				session.close();
		}
	}

	private int findFullPhone(){
	try{
		this.clientList= (this.clientList==null?new ArrayList<ClientDetail>():this.clientList);
			
			if(ClientTool.isMobileNO(this.queryStr)){
				System.out.println(this.clientList.size()+"######");
				ClientFormBean bean =(AdvanceClientService.getInstance().getDetailByPhone(this.queryStr));
				ClientDetail cd = new ClientDetail();
				if(bean!=null){
					cd.setCid(bean.getCid());
					ClientBase cb = bean.getCb();
					cb.setName(cb.getName().substring(0,1)+"**");
					
					cd.setClientBase(cb);
					
					ClientExtend ce = new ClientExtend();
					
					User owner = UserService.getInstance().getUserById(cb.getOwner());
					ce.setMemo("所属销售员("+owner.getTruename()+")|电话("+owner.getPhone()+")");
					cd.setClientExtend(ce);
					
					ClientPhone cp =new ClientPhone();
					cp.setCid(cd.getCid());
					cp.setPhone(this.queryStr);
					
					List<ClientPhone> list = new ArrayList<ClientPhone>();
					list.add(cp);
					cd.setClientPhones(list);
					
				}
				this.clientList.add(cd);
				return 1;
				
			}else{
				this.tip="该号码不存在";
				return 0;
			}
	}catch(Exception e){
		e.printStackTrace();
		this.tip="该号码不存在";
		return 0;
	}
	}

	public String getOrderType() {
		return orderType;
	}

	public void setOrderType(String orderType) {
		this.orderType = orderType;
	}

	public String getQueryType() {
		return queryType;
	}

	public void setQueryType(String queryType) {
		this.queryType = queryType;
	}

	public String getIsDesc() {
		return isDesc;
	}

	public void setIsDesc(String isDesc) {
		this.isDesc = isDesc;
	}

	public Integer getCurPage() {
		return curPage;
	}

	public void setCurPage(Integer curPage) {
		this.curPage = curPage;
	}

	public String getQueryStr() {
		return queryStr;
	}

	public void setQueryStr(String queryStr) {
		this.queryStr = queryStr;
	}

	public Integer getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(Integer totalPage) {
		this.totalPage = totalPage;
	}

	public Integer getPageSize() {
		return pageSize;
	}

	public void setPageSize(Integer pageSize) {
		this.pageSize = pageSize;
	}

	public Integer getTotal() {
		return total;
	}

	public void setTotal(Integer total) {
		this.total = total;
	}

	public Integer getState() {
		return state;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public Integer getCid() {
		return cid;
	}

	public void setCid(Integer cid) {
		this.cid = cid;
	}

	public String getPhone1() {
		return phone1;
	}

	public void setPhone1(String phone1) {
		this.phone1 = phone1;
	}

	public String getPhone2() {
		return phone2;
	}

	public void setPhone2(String phone2) {
		this.phone2 = phone2;
	}

	public String getPhone3() {
		return phone3;
	}

	public void setPhone3(String phone3) {
		this.phone3 = phone3;
	}

	public Integer getPhone1Id() {
		return phone1Id;
	}

	public void setPhone1Id(Integer phone1Id) {
		this.phone1Id = phone1Id;
	}

	public Integer getPhone2Id() {
		return phone2Id;
	}

	public void setPhone2Id(Integer phone2Id) {
		this.phone2Id = phone2Id;
	}

	public Integer getPhone3Id() {
		return phone3Id;
	}

	public void setPhone3Id(Integer phone3Id) {
		this.phone3Id = phone3Id;
	}

	public String getProvinceId() {
		return provinceId;
	}

	public void setProvinceId(String provinceId) {
		this.provinceId = provinceId;
	}

	public String getCityId() {
		return cityId;
	}

	public void setCityId(String cityId) {
		this.cityId = cityId;
	}

	public String getAreaId() {
		return areaId;
	}

	public void setAreaId(String areaId) {
		this.areaId = areaId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}

	public String getMemo() {
		return memo;
	}

	public void setMemo(String memo) {
		this.memo = memo;
	}

	public String[] getChose1() {
		return chose1;
	}

	public void setChose1(String[] chose1) {
		this.chose1 = chose1;
	}

	public String[] getChose2() {
		return chose2;
	}

	public void setChose2(String[] chose2) {
		this.chose2 = chose2;
	}

	public String[] getChose3() {
		return chose3;
	}

	public void setChose3(String[] chose3) {
		this.chose3 = chose3;
	}

	public String getChose4() {
		return chose4;
	}

	public void setChose4(String chose4) {
		this.chose4 = chose4;
	}

	public String getChose5() {
		return chose5;
	}

	public void setChose5(String chose5) {
		this.chose5 = chose5;
	}

	public Integer getChose6() {
		return chose6;
	}

	public void setChose6(Integer chose6) {
		this.chose6 = chose6;
	}

	public ClientDetail getClientDetail() {
		return clientDetail;
	}

	public void setClientDetail(ClientDetail clientDetail) {
		this.clientDetail = clientDetail;
	}

	public List<ClientDetail> getClientList() {
		return clientList;
	}

	public void setClientList(List<ClientDetail> clientList) {
		this.clientList = clientList;
	}

	public String getCjsons() {
		return cjsons;
	}

	public void setCjsons(String cjsons) {
		this.cjsons = cjsons;
	}

	public Integer getPhoneNum() {
		return phoneNum;
	}

	public void setPhoneNum(Integer phoneNum) {
		this.phoneNum = phoneNum;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}




}
